﻿using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace EasyNet.Componets.Core.Http
{
    /// <summary>
    /// HTTP 查询字符串生成器
    /// </summary>
    public class HttpQueryStringBuilder
    {
        #region Fields
        private bool _isSorted;

        private string _value;

        private SortedDictionary<string, string> _sortedDic;

        private Dictionary<string, string> _dic;
        #endregion


        #region Ctor
        public HttpQueryStringBuilder()
        {
            Init(false);
        }

        public HttpQueryStringBuilder(bool isSorted)
        {
            Init(isSorted);
        }

        private void Init(bool isSorted)
        {
            _isSorted = isSorted;
            
            if (_isSorted)
            {
                _sortedDic = new SortedDictionary<string, string>();
            }
            else
            {
                _dic = new Dictionary<string, string>();
            }
        }
        #endregion

        #region Members
        public HttpQueryStringBuilder Add(string key, string value)
        {
            if (!key.IsNullOrEmpty() && !value.IsNullOrEmpty())
            {
                _sortedDic.Add(key, value);

            }
            return this;
        }

        public HttpQueryStringBuilder Add(IDictionary<string, string> dic)
        {
            if (dic == null) return this;

            foreach (var item in dic)
            {
                Add(item.Key, item.Value);
            }

            return this;
        }

        public override string ToString()
        {
            if(string.IsNullOrEmpty(_value))
            {
                var stringBuilder = new StringBuilder();
                foreach (var item in _sortedDic)
                {
                    stringBuilder.Append(item.Key)
                    .Append("=")
                    .Append(item.Value)
                    .Append("&");
                }
                if (stringBuilder.Length > 0) stringBuilder.Remove(stringBuilder.Length - 1, 1);
                _value = stringBuilder.ToString();
            }
            return _value;
        }
        #endregion


    }
}
